[Golang] gorm 2.0 insert on duplicate update


Posted by kitecloud213 on 2020-09-09

最近升級了 gorm 2.0,紀錄一下 on duplicate update 寫法

type TableItem struct {
    ID int // PK
    Amount int
}

func Create(ID int, amount int) error {
    db := dbPool.Get() // 取得已經建立好的 connection
    item := &TableItem{
        ID: ID,
        Amount: amount,
    }
    err := db.Clauses(clause.OnConflict{
        DoUpdates: clause.Assignments(map[string]interface{}{"amount": item.Amount}),
    }).Create(item).Error
    if err != nil {
        return err
    }

    return nil
}

#golang #gorm







Related Posts

程式導師計畫 4th / 第十週複習整理心得

程式導師計畫 4th / 第十週複習整理心得

[day-3]布林、undefined、null/字串數字轉換/比較與邏輯運算子

[day-3]布林、undefined、null/字串數字轉換/比較與邏輯運算子

[第六週] 認識 HTML 及常用標籤 (上)

[第六週] 認識 HTML 及常用標籤 (上)


Comments